package org.x.chat.config;

import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.messaging.*;

@Configuration
public class StompEventListenerConfig {

    /**
     * STOMP 事件监听器工厂
     */
    @Bean
    public ApplicationListener<?> stompEventListeners() {
        return event -> {
            if (event instanceof SessionConnectEvent) {
                handleConnectEvent((SessionConnectEvent) event);
            } else if (event instanceof SessionConnectedEvent) {
                handleConnectedEvent((SessionConnectedEvent) event);
            } else if (event instanceof SessionDisconnectEvent) {
                handleDisconnectEvent((SessionDisconnectEvent) event);
            } else if (event instanceof SessionSubscribeEvent) {
                handleSubscribeEvent((SessionSubscribeEvent) event);
            } else if (event instanceof SessionUnsubscribeEvent) {
                handleUnsubscribeEvent((SessionUnsubscribeEvent) event);
            }
        };
    }

    private void handleConnectEvent(SessionConnectEvent event) {
        // 客户端发起连接请求时触发
        System.out.println("[CONNECT] 连接请求: " + event);
    }

    private void handleConnectedEvent(SessionConnectedEvent event) {
        // 连接成功建立时触发
        String sessionId = getSessionId(event);
        System.out.println("[CONNECTED] 连接成功: sessionId=" + sessionId);
    }

    private void handleDisconnectEvent(SessionDisconnectEvent event) {
        // 连接断开时触发
        String sessionId = event.getSessionId();
        System.out.println("[DISCONNECT] 连接断开: sessionId=" + sessionId);
    }

    private void handleSubscribeEvent(SessionSubscribeEvent event) {
        // 客户端订阅主题时触发
        String sessionId = getSessionId(event);
        String destination = getDestination(event);
        System.out.println("[SUBSCRIBE] 订阅主题: sessionId=" + sessionId +
                ", destination=" + destination);
    }

    private void handleUnsubscribeEvent(SessionUnsubscribeEvent event) {
        // 客户端取消订阅时触发
        String sessionId = getSessionId(event);
        System.out.println("[UNSUBSCRIBE] 取消订阅: sessionId=" + sessionId);
    }

    private String getSessionId(AbstractSubProtocolEvent event) {
        return event.getMessage().getHeaders().get("simpSessionId").toString();
    }

    private String getDestination(SessionSubscribeEvent event) {
        return event.getMessage().getHeaders().get("simpDestination").toString();
    }
}